import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class FavoriteScreen extends StatefulWidget {
  FavoriteScreen({Key key}) : super(key: key);

  @override
  _FavoriteScreenState createState() => _FavoriteScreenState();
}

class _FavoriteScreenState extends State<FavoriteScreen> {
  static const platform = MethodChannel('com.example.com/battery');
  String _batteryLevel = 'Unknown battery level.';

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('收藏')),
      body: Container(
        child: Column(
          children: [
            Container(
              height: 60.0,
              child: Center(
                child: Text('Favorite Screen'),
              ),
            ),
            ElevatedButton(
              onPressed: _getBatteryLevel,
              child: Text('Get Battery Level'),
            ),
            Padding(
              padding: EdgeInsets.only(top: 12.0, bottom: 12.0),
              child: Text(_batteryLevel),
            ),
            ElevatedButton(
              onPressed: _updateAppBadge,
              child: Text('App Badge Update'),
            ),
          ],
        ),
      ),
    );
  }

  void _updateAppBadge() {
    Timer(Duration(seconds: 12), () {
      platform.invokeMethod('setAppBadge', {"badgeCount": 2});
    });
  }

  Future<void> _getBatteryLevel() async {
    String batteryLevel;
    try {
      final result = await platform.invokeMethod<int>('getBatteryLevel');
      batteryLevel = 'Battery level at $result % .';
    } on PlatformException catch (e) {
      batteryLevel = "Failed to get battery level: '${e.message}'.";
    }

    setState(() {
      _batteryLevel = batteryLevel;
    });
  }
}
